package bman.tools;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class JFile 
{
	/**
	 * Writes contents of the parameter into a file with the specified filename. This method will
	 * overwrite existing files.
	 * 
	 * The contents are written into the file as a byte array.
	 *  
	 * @param fileName
	 * @param contents
	 * @throws Exception
	 */
	public static void write(String fileName, String contents) throws Exception
	{
		File f = new File(fileName);
		FileOutputStream fos = new FileOutputStream(f);
		fos.write(contents.getBytes());
		fos.close();
	}
	
	/**
	 * Reads all the contents of a file. The maximum file size in bytes is Integer.MAX_VALUE. 
	 * 
	 * @throws @{java.io.FileNotFoundException} if the file does not exists.
	 */
	public static byte[] read(String fileName) throws Exception
	{
		File f = new File(fileName);
		long length = f.length();
		
		if(length > Integer.MAX_VALUE)
		{
			throw new IOException("The file "+fileName+" exceeds the maximum supported size which is "+Integer.MAX_VALUE);
		}
		
		byte[] b = new byte[(int)length];
		
		FileInputStream fis = new FileInputStream(f);
		BufferedInputStream r = new BufferedInputStream(fis);
		r.read(b);
		
		return b;
	}
}
